/**
 * Copyright (c) 2002-2011 旭鸣信息
 * All rights reserved. 
 * File：ArticlesDaoImpl.java
 * History:
 *       May 11, 2012: Initially created, liuzhi.
 */
package com.xteam.ecsystem.dao.Impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xteam.ecsystem.base.SystemContent;
import com.xteam.ecsystem.dao.IArticlesDao;
import com.xteam.ecsystem.entities.BaseArticleGroup;
import com.xteam.ecsystem.entities.BaseArticleInfo;
import com.xteam.ecsystem.utils.PageCenterStation;

/**
 * 文章数据访问实现类
 * 
 * @author liuzhi
 *
 */
@Repository
public class ArticlesDaoImpl extends DDLPrefix implements IArticlesDao {
	
	@SuppressWarnings("unchecked")
	@Autowired
	private BaseDaoImpl baseDao;

	@SuppressWarnings("unchecked")
	public void delObject(String baiIds) {
		Class clazz = null;
		
		try {
			clazz = Class.forName("com.xteam.ecsystem.entities.BaseArticleInfo");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		List list = new ArrayList();
		String oId[] = baiIds.split(",");
		for (String id : oId) {
			Object obj = this.baseDao.get(clazz, id);
			if (obj != null) {
				list.add(obj);
			}
		}
		
		this.baseDao.deleteAll(list);
	}

	public void saveOrUpdateObject(Object obj, String baiId) {
		try {
			BaseArticleInfo bai = (BaseArticleInfo)obj;
			bai.setBaiTime(new Date());
			
			if (baiId != null && !baiId.equals("") && baiId.length() > 0){
				this.baseDao.saveOrUpdate(bai);
			}else {
				bai.setBaiState(1);
				this.baseDao.save(bai);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public void delBaiImageById(String baiId) {
		Class clazz = null;
		try {
			clazz = Class.forName("com.xteam.ecsystem.entities.BaseArticleInfo");
			
			BaseArticleInfo bai = (BaseArticleInfo)this.baseDao.get(clazz, baiId);
			bai.setBaiImage(null);
			
			this.baseDao.saveOrUpdate(bai);
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public String getBaiById(String baiId) {
		JSONObject jo = new JSONObject();
		try {
			List list = new ArrayList();
			
			String hql = SQL_FROM + BaseArticleInfo.REF + SQL_WHERE +" 1=1 " + SQL_AND + " baiId=?";
			list = this.baseDao.find(hql, new Object[]{baiId});
			
			jo = JSONObject.fromObject((BaseArticleInfo)list.get(0));

		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return jo.toString();
	}

	@SuppressWarnings("unchecked")
	public String getBaiList(int pageIndex, int pageSize, String baiTitle,
			String baiGroup, String baiState) {
		JSONObject jo = new JSONObject();
		try {
			List list = new ArrayList();
			
			// 直接使用连接查询得到的是数组而不是json数据，因此此处的构造函数就是用于构建json类型的数据。
			String hql = SQL_SELECT + " new " + BaseArticleInfo.REF + " (bai.baiId, bai.baiTitle, " 
					+ "bai.baiGroup, bai.baiAuthor, bai.baiOrder, bai.baiDetail, bai.baiAttachname, " 
					+ "bai.baiAttachurl, bai.baiImage, bai.baiTime, bai.baiState, bag.bagName) " 
					+ SQL_FROM + BaseArticleInfo.REF + " as bai, " + BaseArticleGroup.REF + " as bag "  
					+ SQL_WHERE + " bai.baiGroup = bag.bagId ";
			
			String countHQL = SQL_SELECT + " count(*) " + SQL_FROM + BaseArticleInfo.REF 
					+ " as bai, " + BaseArticleGroup.REF + " as bag " + SQL_WHERE 
					+ " bai.baiGroup = bag.bagId ";
			
			if (baiTitle != null && baiTitle.length() > 0
					&& !baiTitle.equals("undefined")
					&& !baiTitle.equals("null")) {
				hql += SQL_AND + " bai.baiTitle " + SQL_LIKE + " ? ";
				countHQL += SQL_AND + " bai.baiTitle " + SQL_LIKE + " ? ";
				list.add("%" + baiTitle + "%");

			}
			
			if (baiGroup != null && baiGroup.length() > 0
					&& !baiGroup.equals("undefined")
					&& !baiGroup.equals("null")
					&& !"-1".equals(baiGroup)) {
				hql += SQL_AND + " bai.baiGroup=? ";
				countHQL += SQL_AND + " bai.baiGroup=? ";
				list.add(baiGroup);

			}
			
			if(baiState != null && baiState.length() > 0
					&& !baiState.equals("undefined")
					&& !baiState.equals("null")){
				if(!"-1".equals(baiState)){
					hql += SQL_AND + " bai.baiState=? ";
					countHQL += SQL_AND + " bai.baiState=? ";
					list.add(Integer.parseInt(baiState));
				}
			}

			PageCenterStation<?> p = (PageCenterStation<?>) this.baseDao.queryList(countHQL, hql, list
					.toArray(), pageIndex * pageSize, pageSize);
			
			jo = JSONObject.fromObject(p);

		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return jo.toString();
	}

	@SuppressWarnings("unchecked")
	public void updateBaiStateById(String baiId) {
		Class clazz = null;
		try {
			clazz = Class.forName("com.xteam.ecsystem.entities.BaseArticleInfo");
			
			BaseArticleInfo bai = (BaseArticleInfo)this.baseDao.get(clazz, baiId);
			if(bai.getBaiState() == 1){
				bai.setBaiState(0);
			}else{
				bai.setBaiState(1);
			}
			
			this.baseDao.saveOrUpdate(bai);
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	public String getBagTreeSelect(String type) {
		JSONArray jarray = new JSONArray();
		List list = new ArrayList();
		try {
			String hql = SQL_FROM + BaseArticleGroup.REF + SQL_WHERE + " 1=1 ";
			list = this.baseDao.find(hql);
			jarray = JSONArray.fromObject(list);
			
			if(type != null && !"".equals(type) && !"null".equals(type)){
				if("add".equals(type)){
					JSONObject top = new JSONObject();
					top.put("bagId", "-1");
					top.put("bagName", "请选择...");
					top.put("bagParent", "0");
					jarray.add(0, top);
				}else if("query".equals(type)){
					JSONObject top = new JSONObject();
					top.put("bagId", "-1");
					top.put("bagName", "所有分类");
					top.put("bagParent", "0");
					jarray.add(0, top);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		return jarray.toString();
	}

	public String getBaiByAttachname(String baiAttachname, String baiId) {
		return null;
	}
	
	/**
	 * @see com.xteam.ecsystem.dao.IArticlesDao#getSystemContent(int, java.lang.String, java.lang.String, java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, String>> getSystemContent(int state, String value, String text, String parent) {
		String hql = "select baiId as " + value + ", baiTitle as " + text + ", '' as " + parent + 
			" from BaseArticleInfo where baiState = " + state;
		return this.baseDao.queryListInMap(hql);
	}
	
	/**
	 * @see com.xteam.ecsystem.dao.IArticlesDao#getSystemContents(java.lang.String, int, int, int)
	 */
	@SuppressWarnings("unchecked")
	public PageCenterStation<SystemContent> getSystemContents(String name, int state, int first, int max) {
		String suffix = " from base_article_info c left join base_article_group p on c.bai_group = p.bag_id " + 
			"where c.bai_state = " + state;
		if (name != null && !"".equals(name)) {
			suffix += " and c.bai_title like '%" + name + "%'";
		}
		
		String countSql = "select count(c.bai_id)" + suffix;
		long count = this.baseDao.queryCountWithSql(countSql);
		
		List<SystemContent> list = new ArrayList<SystemContent>();
		if (count > 0) {
			String querySql = "select c.bai_id as value, c.bai_title as text, p.bag_name as parent" + suffix;
			List<Object[]> data = this.baseDao.queryListWithSql(querySql);
			if (data != null) {
				for (Object[] o : data) {
					String value = (o[0] == null) ? null : o[0].toString();
					String text = (o[1] == null) ? null : o[1].toString();
					String parent = (o[2] == null) ? null : o[2].toString();
					list.add(new SystemContent(value, text, parent));
				}
			}
		}
		
		return new PageCenterStation<SystemContent>(count, list);
	}
}
